/******************************************
 * Include Class for the ID3D10Include Interface
 ******************************************
 * (C) 2010 D.Teeder
 ******************************************/
#include "DXUT.h"
#include <PrecompiledHeader.h>
#include "Include.h"
using namespace d3d11;

HRESULT Include::Open(D3D10_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes)
{
	TRACE("[Include::Open] file: %s\n", pFileName);

	FILE *fp;
//	unsigned int i;

	if (IncludeType & D3D10_INCLUDE_LOCAL)
	{
		// dummy
	}

	if (IncludeType & D3D10_INCLUDE_SYSTEM)
	{
		// dummy
	}

	// get the file stream
	fopen_s( &fp, pFileName, "rb" );
	
	if (fp == NULL)
	{
		TRACE("[Include::Open] file not found!\n");
		return E_FAIL;
	}
	
	// get file size
	*pBytes = getFileSize(fp);

	TRACE("[Include::Open] filesize %d.\n", *pBytes);

	// read file into buffer
	m_pBuffer = (byte *) malloc(*pBytes * sizeof(byte));

	fread_s(m_pBuffer, sizeof(byte) * *pBytes, sizeof(byte), *pBytes, fp);

	fclose(fp);

	*ppData = m_pBuffer;

	return S_OK;
}

HRESULT Include::Close(LPCVOID pData)
{
	TRACE("[Include::Close]\n");

	free(m_pBuffer);
	
	return S_OK;
}

unsigned int Include::getFileSize(FILE *pFile)
{
	// set the file pointer to end of file
	fseek( pFile, 0, SEEK_END );
	
	// get the file size
	unsigned int uiSize = (unsigned int) ftell( pFile );

	// return the file pointer to begin of file if you want to read it
	rewind( pFile );

	return uiSize;
}